package mcore

import (
	"database/sql/driver"
	"fmt"
	"strings"
	"time"
)

type LocalDatetime time.Time

func (ce *LocalDatetime) Value() (driver.Value, error) {
	return ce.Time(), nil
}
func (ce *LocalDatetime) Scan(src any) error {
	switch src.(type) {
	case time.Time:
		*ce = LocalDatetime(src.(time.Time))
		return nil
	case []uint8:
		s := String(src.(string))
		*ce = LocalDatetime((&s).Time())
		return nil
	}
	return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type mmodel.LocalDatetime", src)

}
func (ce *LocalDatetime) UnmarshalJSON(data []byte) (err error) {
	defer func() {
		er := recover()
		if er != nil {
			err = er.(error)
		}
	}()
	*ce = LocalDatetime(StringReadByte(data).Time())
	return nil
}

func (ce *LocalDatetime) MarshalJSON() ([]byte, error) {
	if ce.IsNull() {
		return []byte("\"\""), nil
	}
	str := ce.String()
	if strings.HasSuffix(str, "00:00:00") {
		return []byte(fmt.Sprintf("\"%s\"", str[0:10])), nil
	}
	return []byte(fmt.Sprintf("\"%s\"", str)), nil
}

func (ce *LocalDatetime) String() string {
	return DateUtil.DateTimeToStr(ce.Time())
}

func (ce *LocalDatetime) IsNull() bool {
	t := ce.Time()
	return t.Year() == 1 && t.Month() == 1 && t.Day() == 1
}
func (ce *LocalDatetime) Time() time.Time {
	return time.Time(*ce)
}

func NowLocalDateTime() *LocalDatetime {
	return LocalDateTimeWithTime(DateUtil.NowDateTime())
}
func LocalDateTimeWithTime(data time.Time) *LocalDatetime {
	now := LocalDatetime(data)
	return &now
}
func NowLocalDateTimeStr() String {
	now := LocalDatetime(DateUtil.NowDateTime())
	return String(now.String())
}
func LocalDateTimeWithString(str string) *LocalDatetime {
	s := String(str)
	return LocalDateTimeWithTime((&s).Time())
}
func LocalDateTimeWithUnixMilli(msec int64) *LocalDatetime {
	return LocalDateTimeWithTime(time.UnixMilli(msec))
}

func LocalDateTimeWithUnix(sec int64, nsec int64) *LocalDatetime {
	return LocalDateTimeWithTime(time.Unix(sec, nsec))
}
